package org.gpf.servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;

/**
 * 实现算式验证码的Servlet
 * @author gaopengfei
 * @date 2015-5-21 下午7:53:13
 */
public class MyKaptchaServlet extends HttpServlet implements Servlet{

	private static final long serialVersionUID = -3972137928235167522L;
	private Properties props;
	    private Producer kaptchaProducer;
	    private String sessionKeyValue;
	    
	    public MyKaptchaServlet() {
	         props = new Properties();
	         kaptchaProducer = null;
	         sessionKeyValue = null;
	    }
	    
	    @SuppressWarnings("rawtypes")
		public void init(ServletConfig conf) throws ServletException {
	        super.init(conf);

	        ImageIO.setUseCache(false);

	        Enumeration initParams = conf.getInitParameterNames();
	        while (initParams.hasMoreElements()) {
	            String key = (String) initParams.nextElement();
	            String value = conf.getInitParameter(key);
	            this.props.put(key, value);
	        }

	        Config config = new Config(this.props);
	        this.kaptchaProducer = config.getProducerImpl();
	        this.sessionKeyValue = config.getSessionKey();
	    }

	    public void doGet(HttpServletRequest req, HttpServletResponse resp)
	            throws ServletException, IOException {
	        resp.setDateHeader("Expires", 0L);

	        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

	        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");

	        resp.setHeader("Pragma", "no-cache");

	        resp.setContentType("image/jpeg");

	        String capText = this.kaptchaProducer.createText();
	        String s1 = capText.substring(0, 1);    // 获取随机生成的第一个数字
	        String s2 = capText.substring(1, 2);    // 由于web.xml中配置的验证码字符都是数字，不会发生数字格式化异常
	        int r = Integer.parseInt(s1) + Integer.parseInt(s2);

	        req.getSession().setAttribute(this.sessionKeyValue, String.valueOf(r));    // 将结果存入session

	        BufferedImage bi = this.kaptchaProducer.createImage(s1 + " + " + s2 + " = ?"); // 产生图片

	        ServletOutputStream out = resp.getOutputStream();

	        ImageIO.write(bi, "jpg", out);
	        try {
	            out.flush();
	        } finally {
	            out.close();
	        }
	    }
}
